#include "../../include/db/user_permissions.h"
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/db.h"

int init_permissions_table(sqlite3 *db)
{
    char *sql = "CREATE TABLE IF NOT EXISTS user_permissions ("
                "user_id INTEGER NOT NULL,"
                "file_path TEXT NOT NULL,"
                "read BOOLEAN NOT NULL DEFAULT 0,"
                "write BOOLEAN NOT NULL DEFAULT 0,"
                "PRIMARY KEY (user_id, file_path));";
    return sqlite3_exec(db, sql, NULL, 0, NULL);
}

int check_permission(sqlite3 *db, int user_id, const char *file_path, int required_perm)
{
    sqlite3_stmt *stmt;
    const char *sql = "SELECT read, write FROM user_permissions "
                      "WHERE user_id = ? AND file_path = ?;";

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
        return -1;

    sqlite3_bind_int(stmt, 1, user_id);
    sqlite3_bind_text(stmt, 2, file_path, -1, SQLITE_STATIC);

    int result = -1;
    if (sqlite3_step(stmt) == SQLITE_ROW)
    {
        int has_read = sqlite3_column_int(stmt, 0);
        int has_write = sqlite3_column_int(stmt, 1);

        if ((required_perm & PERM_READ) && !has_read)
            result = 0;
        else if ((required_perm & PERM_WRITE) && !has_write)
            result = 0;
        else
            result = 1;
    }

    sqlite3_finalize(stmt);
    return result;
}

// 添加文件权限
int add_file_permission(sqlite3 *db, int user_id, const char *file_path, int can_read, int can_write, int can_delete)
{
    if (!db || user_id <= 0 || !file_path)
    {
        return -1;
    }

    // 先检查是否已存在该用户对该文件的权限记录
    sqlite3_stmt *stmt;
    const char *sql_check =
        "SELECT id FROM file_permissions WHERE user_id = ? AND file_path = ?;";

    if (sqlite3_prepare_v2(db, sql_check, -1, &stmt, NULL) != SQLITE_OK)
    {
        return -1;
    }

    sqlite3_bind_int(stmt, 1, user_id);
    sqlite3_bind_text(stmt, 2, file_path, -1, SQLITE_STATIC);

    int result = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    if (result == SQLITE_ROW)
    {
        // 已存在记录，更新
        const char *sql_update =
            "UPDATE file_permissions SET can_read = ?, can_write = ?, can_delete = ? "
            "WHERE user_id = ? AND file_path = ?;";

        if (sqlite3_prepare_v2(db, sql_update, -1, &stmt, NULL) != SQLITE_OK)
        {
            return -1;
        }

        sqlite3_bind_int(stmt, 1, can_read);
        sqlite3_bind_int(stmt, 2, can_write);
        sqlite3_bind_int(stmt, 3, can_delete);
        sqlite3_bind_int(stmt, 4, user_id);
        sqlite3_bind_text(stmt, 5, file_path, -1, SQLITE_STATIC);
    }
    else
    {
        // 不存在记录，插入
        const char *sql_insert =
            "INSERT INTO file_permissions (user_id, file_path, can_read, can_write, can_delete) "
            "VALUES (?, ?, ?, ?, ?);";

        if (sqlite3_prepare_v2(db, sql_insert, -1, &stmt, NULL) != SQLITE_OK)
        {
            return -1;
        }

        sqlite3_bind_int(stmt, 1, user_id);
        sqlite3_bind_text(stmt, 2, file_path, -1, SQLITE_STATIC);
        sqlite3_bind_int(stmt, 3, can_read);
        sqlite3_bind_int(stmt, 4, can_write);
        sqlite3_bind_int(stmt, 5, can_delete);
    }

    result = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    return (result == SQLITE_DONE) ? 0 : -1;
}

// 检查文件操作权限
int check_file_permission(sqlite3 *db, int user_id, const char *file_path, int operation_type)
{
    if (!db || user_id <= 0 || !file_path)
    {
        return -1;
    }

    // 检查用户权限级别，管理员(权限级别>=10)可以访问所有文件
    int permission_level = get_user_permission_level(db, user_id);
    if (permission_level >= 10)
    {
        return 1; // 管理员拥有全部权限
    }

    // 查询直接匹配的权限
    sqlite3_stmt *stmt;
    const char *sql_direct =
        "SELECT can_read, can_write, can_delete FROM file_permissions "
        "WHERE user_id = ? AND file_path = ?;";

    if (sqlite3_prepare_v2(db, sql_direct, -1, &stmt, NULL) != SQLITE_OK)
    {
        return -1;
    }

    sqlite3_bind_int(stmt, 1, user_id);
    sqlite3_bind_text(stmt, 2, file_path, -1, SQLITE_STATIC);

    int result = sqlite3_step(stmt);

    if (result == SQLITE_ROW)
    {
        // 找到直接匹配的权限
        int can_read = sqlite3_column_int(stmt, 0);
        int can_write = sqlite3_column_int(stmt, 1);
        int can_delete = sqlite3_column_int(stmt, 2);
        sqlite3_finalize(stmt);

        if (operation_type == OPERATION_READ)
        {
            return can_read;
        }
        else if (operation_type == OPERATION_WRITE)
        {
            return can_write;
        }
        else if (operation_type == OPERATION_DELETE)
        {
            return can_delete;
        }
        else
        {
            return -1; // 未知操作类型
        }
    }

    sqlite3_finalize(stmt);

    // 查询目录级别权限（查找最近的父目录权限）
    char current_path_for_parent_check[1024];
    strncpy(current_path_for_parent_check, file_path, sizeof(current_path_for_parent_check) - 1);
    current_path_for_parent_check[sizeof(current_path_for_parent_check) - 1] = '\0';

    while (1)
    {
        char *last_slash = strrchr(current_path_for_parent_check, '/');

        if (last_slash == NULL)
        { // No more slashes, should not happen if path starts with /
            break;
        }

        // Determine the parent path to check
        if (last_slash == current_path_for_parent_check)
        { // Path is like "/file" or already "/"
            if (current_path_for_parent_check[1] == '\0')
            { // Path is exactly "/"
              // Already checked root or about to check, and no further parent.
              // If we are here, means direct check for "/" failed or was not specific enough.
              // However, the loop should query for "/" and then break.
            }
            else
            {
                // Path was like "/file", parent is "/"
                strcpy(current_path_for_parent_check, "/");
            }
        }
        else
        { // Path is like "/a/b/file", parent is "/a/b"
            *last_slash = '\0';
        }

        // fprintf(stdout, "[PERM_DEBUG] Checking parent path: %s for original_path: %s\n", current_path_for_parent_check, file_path);

        // 查询该父目录的权限
        const char *sql_parent =
            "SELECT can_read, can_write, can_delete FROM file_permissions "
            "WHERE user_id = ? AND file_path = ?;";
        sqlite3_stmt *stmt_parent;
        if (sqlite3_prepare_v2(db, sql_parent, -1, &stmt_parent, NULL) != SQLITE_OK)
        {
            // fprintf(stderr, "[PERM_DEBUG] Failed to prepare parent perm check: %s\n", sqlite3_errmsg(db));
            return -1; // SQL error
        }

        sqlite3_bind_int(stmt_parent, 1, user_id);
        sqlite3_bind_text(stmt_parent, 2, current_path_for_parent_check, -1, SQLITE_STATIC);

        int step_result = sqlite3_step(stmt_parent);
        if (step_result == SQLITE_ROW)
        {
            int can_read = sqlite3_column_int(stmt_parent, 0);
            int can_write = sqlite3_column_int(stmt_parent, 1);
            int can_delete = sqlite3_column_int(stmt_parent, 2);
            sqlite3_finalize(stmt_parent);
            // fprintf(stdout, "[PERM_DEBUG] Found permission for parent %s: read=%d, write=%d, delete=%d\n", current_path_for_parent_check, can_read, can_write, can_delete);
            if (operation_type == OPERATION_READ)
                return can_read;
            else if (operation_type == OPERATION_WRITE)
                return can_write;
            else if (operation_type == OPERATION_DELETE)
                return can_delete;
            else
                return -1; // Unknown operation type
        }
        sqlite3_finalize(stmt_parent);

        if (strcmp(current_path_for_parent_check, "/") == 0)
        { // If we just checked root, stop.
            break;
        }
    }

    // 如果没有找到任何权限设置，默认拒绝访问
    // fprintf(stdout, "[PERM_DEBUG] No specific or parent permission found for %s. Denying.\n", file_path);
    return 0;
}

// 列出用户可访问的文件
int list_user_accessible_files(sqlite3 *db, int user_id, char ***file_list, int *count)
{
    if (!db || user_id <= 0 || !file_list || !count)
    {
        return -1;
    }

    // 先获取用户权限级别
    int permission_level = get_user_permission_level(db, user_id);

    // 查询语句
    const char *sql;
    if (permission_level >= 10)
    {
        // 管理员可以看到所有文件
        sql = "SELECT file_path FROM files ORDER BY file_path;";
    }
    else
    {
        // 普通用户只能看到有权限的文件
        sql = "SELECT DISTINCT f.file_path FROM files f "
              "INNER JOIN file_permissions p ON p.file_path = f.file_path "
              "WHERE p.user_id = ? AND p.can_read = 1 "
              "ORDER BY f.file_path;";
    }

    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
    {
        return -1;
    }

    // 绑定参数（如果是普通用户）
    if (permission_level < 10)
    {
        sqlite3_bind_int(stmt, 1, user_id);
    }

    // 分配内存以存储结果
    int max_files = 100; // 初始容量
    *file_list = (char **)malloc(max_files * sizeof(char *));
    if (!*file_list)
    {
        sqlite3_finalize(stmt);
        return -1;
    }

    *count = 0;

    // 读取结果
    while (sqlite3_step(stmt) == SQLITE_ROW)
    {
        const char *file_path = (const char *)sqlite3_column_text(stmt, 0);

        // 扩容
        if (*count >= max_files)
        {
            max_files *= 2;
            char **new_list = (char **)realloc(*file_list, max_files * sizeof(char *));
            if (!new_list)
            {
                // 内存分配失败，清理并返回
                for (int i = 0; i < *count; i++)
                {
                    free((*file_list)[i]);
                }
                free(*file_list);
                *file_list = NULL;
                *count = 0;
                sqlite3_finalize(stmt);
                return -1;
            }
            *file_list = new_list;
        }

        // 复制文件路径
        (*file_list)[*count] = strdup(file_path);
        if (!(*file_list)[*count])
        {
            // 内存分配失败，清理并返回
            for (int i = 0; i < *count; i++)
            {
                free((*file_list)[i]);
            }
            free(*file_list);
            *file_list = NULL;
            *count = 0;
            sqlite3_finalize(stmt);
            return -1;
        }

        (*count)++;
    }

    sqlite3_finalize(stmt);
    return 0;
}